package org.ms.mconf.server.springboot.configuration;

import lombok.extern.slf4j.Slf4j;
import org.ms.mconf.server.springboot.filter.LanguageFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Configuration
public class StaticConfig extends WebMvcConfigurerAdapter {

    @Value("${mconf.language}")
    private String language;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

    @Bean
    public FilterRegistrationBean myFilterRegistration() throws Exception {
        Map<String, String> resources = new HashMap<>();
        String resourceName = (StringUtils.isEmpty(language) ? "en_US" : language) + ".properties";
        Properties properties = PropertiesLoaderUtils.loadAllProperties(resourceName);
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            resources.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }

        LanguageFilter languageFilter = new LanguageFilter();
        languageFilter.setResources(resources);

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(languageFilter);
        registration.addUrlPatterns("/*");
        registration.setName("languageFilter");
        registration.setOrder(1);
        return registration;
    }

}
